local addon, ns = ...
local C = ns.shared.color
local L = ns.L

local ds_onevent = function (self)
	local name = L["No Spec!"]
	local icon = GetItemIcon(7516)
	local spec = GetSpecialization()
	local _ = nil
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["Dualspec"])

	if  spec ~= nil then
		 _, name, _, icon, _, _ = GetSpecializationInfo(spec)
	end
	dataobj.text = name
	dataobj.icon = icon
end


local ds_events = {
	"PLAYER_LOGIN",
	"ACTIVE_TALENT_GROUP_CHANGED",
	"PLAYER_ENTERING_WORLD",

	"SKILL_LINES_CHANGED",
	"CHARACTER_POINTS_CHANGED",
	"PLAYER_TALENT_UPDATE",
}


local ds_onclick = function (self, btn)
	if btn == "RightButton" then
		SetActiveSpecGroup(abs(GetActiveSpecGroup()-3))
	else
		--ToggleTalentFrame()
		-- Code from Silverwind to solve glyph frame taint.
		UIParentLoadAddOn"Blizzard_TalentUI"
		ToggleFrame(PlayerTalentFrame)
		PlayerTalentFrameTab1:GetScript("OnClick")(PlayerTalentFrameTab1,"LeftButton")
	end
end


local ds_tooltip = function (t)
	t:AddLine(L["Talents"])

	local activeSpec = GetSpecialization()
	local numberSpecs = GetNumSpecGroups()
	local specs = {	}
		
	for i=1, numberSpecs do
		specs["spec" .. i] = GetSpecialization(false,false,i)
	end

	if specs.spec1 == nil and specs.spec2 == nil then
		t:AddLine(L["You have not trained a specialisation."])
	else
		for k, v in pairs(specs) do
			local _, name, _, icon, _, _ = GetSpecializationInfo(v)
			if v == activeSpec then
				t:AddDoubleLine(name, L["Active"])
			else
				t:AddDoubleLine(name, "")
			end

			t:AddTexture(icon)
		end
	end

	t:AddLine(C.dkgreen(L["Hint: Left-click to show the talents pane."]))
	t:AddLine(C.dkgreen(L["Right-click to switch talents."]))
end


Broker_Everything:Register(L["Dualspec"],
	GetItemIcon(7516),
	0,
	ds_onevent,
	ds_events,
	ds_onclick,
	ds_tooltip,
	ds_onevent, 
	5)

